<template>
  <div class="edu-page-warp subject-dialog">
    <edu-dialog :title="itemInfo.actionType === 'ADD' ? $t('graduationDesign.add'): $t('graduationDesign.modify')" size="medium" @close="closeDialog" :visible="subjectDialogVisible">
      <el-form :model="subjectForm" ref="subjectForm" :rules="subjectRules" label-position="right" label-suffix="：" label-width="145px">
        <el-row v-for="(item, index) in subjectForm.subjectList" :key="item.id">
          <div v-if="!item.deleteStatus">
            <el-col :span="12">
              <el-form-item
                :label="!index ? itemInfo.label : ''"
                :prop="!index ? ('subjectList.' + index + '.value') : ''"
                :rules="!index ? subjectRules.value : []">
                <el-input v-model="item.value"
                          maxlength="20"
                          @blur="handleValueChange(item.value, index)"
                          class="subject-input"
                          :placeholder="$t('graduationDesign.pleaseEnter')"/>
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <div class="subject-wave-line"></div>
            </el-col>
            <el-col :span="11">
              <el-form-item label-width="70px">
                <el-button type="primary" icon="el-icon-plus" v-if="index === 0" @click="onAddItem">{{$t('graduationDesign.addTo')}}</el-button>
                <el-button type="danger" icon="el-icon-minus" v-else @click="onDeleteItem(item, index)">{{$t('graduationDesign.delete')}}</el-button>
              </el-form-item>
            </el-col>
          </div>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('graduationDesign.applicableGraduationYear')" prop="startYear">
              <el-date-picker class="dateclass" clearable v-model="subjectForm.startYear" value-format="yyyy" type="year" :placeholder="$t('graduationDesign.pleaseChoose')">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <div class="subject-wave-line">~</div>
          </el-col>
          <el-col :span="11">
            <el-form-item label-width="70px">
              <el-date-picker class="dateclass" clearable v-model="subjectForm.endYear" value-format="yyyy" type="year" :placeholder="$t('graduationDesign.pleaseChoose')">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="buttons">
        <el-button @click="closeDialog">{{$t('graduationDesign.cancel')}}</el-button>
        <el-button type="primary" @click="onSubmit">{{$t('graduationDesign.confirm')}}</el-button>
      </div>
    </edu-dialog>
  </div>
</template>
<script>
export default {
  props: {
    subjectDialogVisible: {
      type: Boolean,
      default: false
    },
    itemInfo: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      subjectForm: {
        subjectList: [{ value: "", deleteStatus: false }],
        startYear: '',
        endYear: ''
      },
      subjectRules: {
        value: [{ required: true, message: this.$t('graduationDesign.pleaseEnter'), trigger: "blur" }],
        startYear: [{ required: true, message: this.$t('graduationDesign.pleaseChoose'), trigger: "change" }]
      }
    };
  },
  mounted() { },
  methods: {
    setSubjectForm (subjectForm) {
      this.subjectForm = subjectForm;
    },
    handleValueChange(val, index) {
      if (!_.isEmpty(val) && index === 0) {
        const field = 'subjectList.0.value';
        this.$nextTick(() => {
          this.$refs.subjectForm.clearValidate(field);
        });
      }
    },
    onSubmit() {
      const paramsData = [];
      this.subjectForm.subjectList.forEach(item => {
        const subjectObj = {
          startYear: this.subjectForm.startYear,
          endYear: this.subjectForm.endYear,
          id: item.id,
          deleteStatus: item.deleteStatus
        };
        subjectObj[this.itemInfo.value] = item.value;
        paramsData.push(subjectObj);
      });
      const params = {
        startYear: this.subjectForm.startYear,
        endYear: this.subjectForm.endYear,
        list: paramsData
      };
      this.$emit("subjectSubmit", params);
    },
    // 校验添加项
    validateAddItem() {
      let isAddAvailable = true;
      let dataset = [];
      this.subjectForm.subjectList.forEach(item => {
        if (_.isEmpty(item.value)) {
          this.$message.warning(this.$t('graduationDesign.pleaseEnter') + this.itemInfo.label);
          isAddAvailable = false;
        }
        if (!dataset.includes(item.value)) {
          dataset.push(item.value);
        }
      });
      if (!isAddAvailable) {
        return false;
      }
      // subjectList内部不能重复
      if (this.subjectForm.subjectList.length > 1) {
        if (dataset.length < this.subjectForm.subjectList.length) {
          this.$message.warning(this.itemInfo.label + this.$t('graduationDesign.contentCannotRepeat'));
          isAddAvailable = false;
        }
      }
      return isAddAvailable;
    },
    onAddItem() {
      if (!this.validateAddItem()) {
        return false;
      };
      const index = this.subjectForm.subjectList.length;
      const addItem = {
        value: "",
        deleteStatus: false
      };
      // 新增一条
      this.subjectForm.subjectList.push(addItem);
      this.$forceUpdate();
    },
    onDeleteItem(row, index) {
      if (this.itemInfo.actionType === "ADD" || (!row.id && row.id !== 0)) {
        this.subjectForm.subjectList.splice(index, 1);
      } else if (this.itemInfo.actionType === "EDIT" && (row.id || row.id === 0)) {
        // 编辑时带有id，删除时是软删除
        this.subjectForm.subjectList.forEach(item => {
          if (row.id === item.id) {
            item.deleteStatus = true;
            this.subjectForm.subjectList.splice(index, 1, item);
          }
        });
      }
      this.$forceUpdate();
    },
    closeDialog() {
      this.$emit("subjectClose");
    }
  }
};
</script>
<style lang="scss" scoped>
.subject-dialog {
    .subject-input {
        width: 100%;
    }
    .dateclass {
        width: 100%;
    }
    .subject-wave-line {
        text-align: center;
        width: 100px;
        margin: 8px auto;
    }
}
</style>
